#!/usr/bin/ruby

size = 10
$max = 20
$hitchar = 'X'
$misschar = ' '
$interval = 0.25

def disk_width( n ) 
  return n*2+1
end

$width = disk_width( $max )

def print_disk( n )
  st = $width/2-n
  en = $width/2+n
  for i in 1..$width do
    print ( i > st && i < en ) ? $hitchar : $misschar
  end
end

def print_pegs( pegs )
  system "clear"
  $max.downto(0) {
    |tier|
    for peg in pegs do
      if peg.size() > tier then
	print_disk peg[tier]
      else
	print_disk 0
      end
    end
    print "\n"
  }
  sleep $interval
end

class Hanoi

  def initialize(size = 4 )
    @size = size
    a = Array.new()
    size.downto(1) { |i|; a << i }
    @pegs = [ a, Array.new(), Array.new() ]
  end

  def go( )
    print_pegs( @pegs )
    hanoi( @size, 0, 1, 2 )
    initialize( @size )
  end

  def hanoi( n, f, t, u )
    if ( n <= 1 ) 
      @pegs[t].push(@pegs[f].pop)
      print_pegs( @pegs )
    else
      hanoi( n-1, f, u, t )
      hanoi(   1, f, t, u ) 
      hanoi( n-1, u, t, f ) 
    end
  end

end

h = Hanoi.new(size)
h.go()

